package cn.iocoder.yudao.module.scrm.controller.admin.customer;

import cn.hutool.core.collection.CollUtil;
import cn.iocoder.yudao.framework.common.util.collection.MapUtils;
import cn.iocoder.yudao.framework.common.util.number.NumberUtils;
import cn.iocoder.yudao.module.scrm.controller.admin.customer.vo.CustomerRespVO;
import cn.iocoder.yudao.module.scrm.controller.admin.customer.vo.customerrepository.*;
import cn.iocoder.yudao.module.scrm.dal.dataobject.customer.CustomerDO;
import cn.iocoder.yudao.module.scrm.dal.dataobject.customer.customerrepository.CustomerRepositoryDO;
import cn.iocoder.yudao.module.scrm.dal.dataobject.customer.customerrepository.CustomerRepositoryRuleDO;
import cn.iocoder.yudao.module.scrm.service.customer.CustomerService;
import cn.iocoder.yudao.module.scrm.service.customer.customerrepository.CustomerRepositoryService;
import cn.iocoder.yudao.module.system.api.dept.DeptApi;
import cn.iocoder.yudao.module.system.api.dept.dto.DeptRespDTO;
import cn.iocoder.yudao.module.system.api.user.AdminUserApi;
import cn.iocoder.yudao.module.system.api.user.dto.AdminUserRespDTO;
import com.fasterxml.jackson.core.JsonProcessingException;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.security.access.prepost.PreAuthorize;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Operation;

import javax.annotation.security.PermitAll;
import javax.validation.constraints.*;
import javax.validation.*;
import javax.servlet.http.*;
import java.util.*;
import java.io.IOException;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;

import cn.iocoder.yudao.framework.excel.core.util.ExcelUtils;

import cn.iocoder.yudao.framework.operatelog.core.annotations.OperateLog;

import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.convertListByFlatMap;
import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.convertSet;
import static cn.iocoder.yudao.framework.operatelog.core.enums.OperateTypeEnum.*;



@Tag(name = "管理后台 - 客户库")
@RestController
@RequestMapping("/scrm/customer-repository")
@Validated
public class CustomerRepositoryController {

    @Resource
    private CustomerRepositoryService customerRepositoryService;

    @Resource
    private DeptApi deptApi;


    @PostMapping("/create")
    @Operation(summary = "创建客户库")
    @PreAuthorize("@ss.hasPermission('scrm:customer-repository:create')")
    public CommonResult<Integer> createCustomerRepository(@Valid @RequestBody CustomerRepositorySaveReqVO createReqVO) {
        return success(customerRepositoryService.createCustomerRepository(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新客户库")
    @PreAuthorize("@ss.hasPermission('scrm:customer-repository:update')")
    public CommonResult<Boolean> updateCustomerRepository(@Valid @RequestBody CustomerRepositorySaveReqVO updateReqVO) {
        customerRepositoryService.updateCustomerRepository(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除客户库")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('scrm:customer-repository:delete')")
    public CommonResult<Boolean> deleteCustomerRepository(@RequestParam("id") Integer id) {
        customerRepositoryService.deleteCustomerRepository(id);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得客户库")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('scrm:customer-repository:query')")
    public CommonResult<CustomerRepositoryRespVO> getCustomerRepository(@RequestParam("id") Integer id) {
        CustomerRepositoryDO customerRepository = customerRepositoryService.getCustomerRepository(id);
        return CommonResult.success(buildCustomerRepositoryDetail(customerRepository));

    }

    @GetMapping("/page")
    @Operation(summary = "获得客户库分页")
    @PreAuthorize("@ss.hasPermission('scrm:customer-repository:query')")
    public CommonResult<PageResult<CustomerRepositoryRespVO>> getCustomerRepositoryPage(@Valid CustomerRepositoryPageReqVO pageReqVO) {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        PageResult<CustomerRepositoryDO> pageResult = customerRepositoryService.getCustomerRepositoryPage(pageReqVO);
        // 拼接数据
        return success(new PageResult<>(buildCustomerRepositoryDetailList(pageResult.getList()), pageResult.getTotal()));
    }

    //单个查询的详情
    private CustomerRepositoryRespVO buildCustomerRepositoryDetail(CustomerRepositoryDO customerDO) {
        if (customerDO == null) {
            return null;
        }
        return buildCustomerRepositoryDetailList(Collections.singletonList(customerDO)).get(0);
    }

    //分页的详情
    public List<CustomerRepositoryRespVO> buildCustomerRepositoryDetailList(List<CustomerRepositoryDO> list) {
        if (CollUtil.isEmpty(list)) {
            return Collections.emptyList();
        }
        // 1.1 批量获取所有部门 ID 并查询部门信息
        Set<Long> deptIds = list.stream()
                .flatMap(repositoryDO -> repositoryDO.getDeptIds().stream())
                .collect(Collectors.toSet());
        Map<Long, DeptRespDTO> deptMap = deptApi.getDeptMapNotCheckDataPermission(deptIds);

        // 2. 转换成 VO
        return list.stream().map(repositoryDO -> {
            // 2.1 处理部门名称
            List<String> deptNames = repositoryDO.getDeptIds().stream()
                    .map(deptMap::get)
                    .filter(Objects::nonNull) // 过滤掉空值
                    .map(DeptRespDTO::getName)
                    .collect(Collectors.toList());

            // 2.2 转换为 CustomerRepositoryRespVO 对象
            CustomerRepositoryRespVO vos = BeanUtils.toBean(repositoryDO, CustomerRepositoryRespVO.class);
            vos.setDeptNames(deptNames);  // 假设有 setDeptNames 方法
            return vos;
        }).collect(Collectors.toList());
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出客户库 Excel")
    @PreAuthorize("@ss.hasPermission('scrm:customer-repository:export')")
    @OperateLog(type = EXPORT)
    public void exportCustomerRepositoryExcel(@Valid CustomerRepositoryPageReqVO pageReqVO,
              HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<CustomerRepositoryDO> list = customerRepositoryService.getCustomerRepositoryPage(pageReqVO).getList();
        // 导出 Excel
        ExcelUtils.write(response, "SCRM客户库.xls", "数据", CustomerRepositoryRespVO.class,
                        buildCustomerRepositoryDetailList(list));
    }

    // ==================== 子表（客户库规则） ====================

    @GetMapping("/customer-repository-rule/list-by-customer-repository-id")
    @Operation(summary = "获得客户库规则列表")
    @Parameter(name = "customerRepositoryId", description = "关联的客户库id")
    @PreAuthorize("@ss.hasPermission('scrm:customer-repository:query')")
    public CommonResult<List<CustomerRepositoryRuleDO>> getCustomerRepositoryRuleListByCustomerRepositoryId(@RequestParam("customerRepositoryId") Integer customerRepositoryId) {
        return success(customerRepositoryService.getCustomerRepositoryRuleListByCustomerRepositoryId(customerRepositoryId));
    }

    @GetMapping("/deptUseScopeByType")
    @Operation(summary = "获取部门的使用范围")
    @PermitAll
    public CommonResult<List<DeptUseScopeByTypeRespVo>> deptUseScopeByType(@Valid DeptUseScopeByTypeReqVo reqVo) throws JsonProcessingException {
        return success(customerRepositoryService.deptUseScopeByType(reqVo));
    }




}